package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Bitmap
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.graphics.Palette
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.FSheetContract
import fm.dongman.animefm.contractlib.contract.MyContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.FSheetListAdapter
import fm.dongman.animefm.view.adapter.FSheetSpecialAdapter
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.SheetLabelModel
import fm.dongman.modellib.model.UserModel
import fm.dongman.presenterlib.presenter.FSheetPresenter
import kotlinx.android.synthetic.main.fragment_find_sheet.*
import org.jetbrains.anko.onClick

/**
 * 发现->漫单页面
 * Created by shize on 2017/9/28.
 */
class FSheetFragment : BaseFragment(), FSheetContract.IFSheetView {
    private lateinit var mPresenter: FSheetContract.IFSheetPresenter

    private val mLabels: ArrayList<IModel.ISheetLabelModel> = ArrayList() // 分类标签
    private lateinit var mLabelAdapter: SheetLabelAdapter // 分类标签适配器

    private val mSpecials: ArrayList<IModel.ISheetModel> = ArrayList() // 专题列表
    private lateinit var mSpecialAdapter: FSheetSpecialAdapter // 专题列表适配器

    private val mMasters: ArrayList<IModel.IUserModel> = ArrayList() // 漫单达人
    private lateinit var mMasterAdapter: SheetMasterAdapter // 漫单达人适配器

    private val mSheets: ArrayList<IModel.ISheetModel> = ArrayList() // 漫单列表
    private lateinit var mSheetAdapter: FSheetListAdapter // 漫单列表适配器

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_find_sheet, container, false)
        FSheetPresenter(this, Injection.provideFSheetRepository(container!!.context))
        return fragment!!
    }

    override fun setPresenter(presenter: FSheetContract.IFSheetPresenter) {
        mPresenter = presenter
    }

    override fun initData() {
        onStateChanged(MultiStateLayout.LOADING)
    }

    override fun bindData() {
        bindSwipe()
        bindMoreBtn()
        bindAdapter()

        mPresenter.startLoad()
    }

    /**
     * 绑定更多漫单/专题按钮
     */
    private fun bindMoreBtn() {
        mFSheetMore.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_LIST),
                    Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, SheetListFragment.TYPE_MANDAN)),
                    false)
        }
        mFTopicMore.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_LIST),
                    Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, SheetListFragment.TYPE_SPEC)),
                    false)
        }
    }

    /**
     * 绑定刷新控件
     */
    private fun bindSwipe() {
        mSrlSheetLayout.setColorSchemeResources(R.color.primary)
        mSrlSheetLayout.setOnRefreshListener {
            mPresenter.refreshPage()
        }
    }

    /**
     * 绑定适配器
     */
    private fun bindAdapter() {
        mLabelAdapter = SheetLabelAdapter(mLabels, activity)
        mRcFindSheet.adapter = mLabelAdapter
        mRcFindSheet.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)

        mSpecialAdapter = FSheetSpecialAdapter(mSpecials, activity)
        mRcFindAnimeSpecial.adapter = mSpecialAdapter
        mRcFindAnimeSpecial.layoutManager = GridLayoutManager(activity, 1, GridLayoutManager.VERTICAL, false)

        mMasterAdapter = SheetMasterAdapter(mMasters, activity)
        mRcFindAnimeMaster.adapter = mMasterAdapter
        mRcFindAnimeMaster.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)

        mSheetAdapter = FSheetListAdapter(mSheets, activity)
        mRcFindAnimeSheet.adapter = mSheetAdapter
        mRcFindAnimeSheet.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    override fun showNoNetwork() {
        mSrlSheetLayout?.isRefreshing = false
        mFSheetMultiStateLayout?.changeState(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        mSrlSheetLayout?.isRefreshing = false
//        ToastHelper.getInstance(activity).showError("发现->漫单页面")
    }

    override fun showFSheetLabels(labels: List<IModel.ISheetLabelModel>) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mLabels.clear()
        mLabels.addAll(labels)
        mLabelAdapter.notifyDataSetChanged()
    }

    override fun showFSheetSpecials(specials: List<IModel.ISheetModel>) {
        mSpecials.clear()
        mSpecials.addAll(specials)
        mSpecialAdapter.notifyDataSetChanged()
    }

    override fun showFSheetMasters(masters: List<IModel.IUserModel>) {
        mMasters.clear()
        mMasters.addAll(masters)
        mMasterAdapter.notifyDataSetChanged()
    }

    override fun showFSheets(sheets: List<IModel.ISheetModel>) {
        mSheets.clear()
        mSheets.addAll(sheets)
        mSheetAdapter.notifyDataSetChanged()
    }

    /**
     * 加载完成
     */
    private fun onStateChanged(state: Int) {
        mSrlSheetLayout?.isRefreshing = false
        mFSheetMultiStateLayout?.changeState(state)
    }

    companion object {
        private var FRAGMENT_INSTANCE: FSheetFragment? = null

        /**
         * 获取实例
         */
        fun getInstance(): FSheetFragment {
            if (FRAGMENT_INSTANCE == null) {
                FRAGMENT_INSTANCE = FSheetFragment()
            }
            return FRAGMENT_INSTANCE!!
        }

        /**
         * 销毁实例
         */
        fun destroyInstance() {
            FRAGMENT_INSTANCE = null
        }
    }

    /**
     * 漫单达人 adapter
     * Created by Administrator on 2017/10/15.
     */
    private class SheetMasterAdapter(private val mListMaster: List<IModel.IUserModel>,
                                     private val mContext: Context)
        : RecyclerView.Adapter<SheetMasterAdapter.SheetMasterViewHolder>() {
        @SuppressLint("InflateParams")
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SheetMasterViewHolder =
                SheetMasterViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_find_anime_master, null))

        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: SheetMasterViewHolder, position: Int) {
            val user = mListMaster[position] as UserModel
            Glide.with(mContext).load(user.avatarUrl).asBitmap().into(object : SimpleTarget<Bitmap>() {
                override fun onResourceReady(resource: Bitmap, glideAnimation: GlideAnimation<in Bitmap>) {
                    Palette.from(resource).generate { palette ->
                        val defColor = ContextCompat.getColor(mContext, R.color.primary)
                        val color = palette.getMutedColor(defColor)
                        holder.mUserName.setTextColor(color)
                        holder.mTintBg.backgroundTintList = ColorStateList.valueOf(color)
                    }
                }
            })
            Glide.with(mContext).load(user.avatarUrl).into(holder.mAvatarUrl)
            holder.mUserName.text = user.userName
            holder.mMandanCount.text = "漫单数：" + user.sheetCount
            holder.itemView.onClick {
                //   点击头像进入用户详细信息界面
                if (MyContract.USER_ID == null) {
                    val intent = Intent(mContext, SingleActivity::class.java)
                    intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_LOGIN)
                    ActivityHelper.startActivity(mContext as Activity, intent)
                    return@onClick
                }
                ActivityHelper.startActivity(mContext as Activity, SingleActivity::class.java, mapOf(
                        Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_USER_INFO),
                        Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, user.userId)
                ), false)
            }
        }

        override fun getItemCount(): Int = mListMaster.size

        private class SheetMasterViewHolder(MasterView: View) : RecyclerView.ViewHolder(MasterView) {
            val mAvatarUrl: ImageView = MasterView.findViewById(R.id.mIvAvatarUrl) as ImageView
            val mUserName: TextView = MasterView.findViewById(R.id.mTvUserName) as TextView
            val mMandanCount: TextView = MasterView.findViewById(R.id.mTvUserFansNum) as TextView
            var mTintBg: View = MasterView.findViewById(R.id.mRlTintBg);
        }
    }

    /**
     * 标签分类 adapter
     * Created by Administrator on 2017/10/14.
     */
    private class SheetLabelAdapter(private val mListFindArticle: List<IModel.ISheetLabelModel>, private val context: Context)
        : RecyclerView.Adapter<SheetLabelAdapter.SheetLabelViewHolder>() {
        @SuppressLint("InflateParams")
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SheetLabelViewHolder =
                SheetLabelViewHolder(LayoutInflater.from(context).inflate(R.layout.item_find_tagclass, null))

        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: SheetLabelViewHolder, position: Int) {
            val sheet = mListFindArticle[position] as SheetLabelModel
            holder.mTitle.text = "# " + sheet.tagName + "#"
            Glide.with(context).load(sheet.tagImg).bitmapTransform(CenterCrop(context), GlideRoundTransform(context, 2)).into(holder.mCover)
            holder.itemView.onClick {
                ActivityHelper.startActivity(context as Activity, SingleActivity::class.java, mapOf(
                        Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_LABEL_SHEET_LIST),
                        Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, sheet.tagName),
                        Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, sheet.tagId)
                ), false)
            }
        }

        override fun getItemCount(): Int = mListFindArticle.size

        private class SheetLabelViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val mTitle = itemView.findViewById(R.id.mTvSheetTagTitle) as TextView
            val mCover = itemView.findViewById(R.id.mIvSheetTagCover) as ImageView
        }
    }
}